<?php

namespace App\Service\CallingCards;

use App\Library\FeiShu\SendFs;
use App\Models\FeishuCallingCard\FeishuCallingCardFranchiseeClue;
use EasyWeChat\Kernel\Http\StreamResponse;

class WechatService
{
    /**
     * 生成微信小程序二维码
     *
     * @param string $userId 用户 id
     * @return string
     * @throws \Exception
     */
    public static function genCallingQrCode(string $userId): string
    {
        $scene    = 'cardId=' . $userId;
        $response = app('callingCardsWechat')->app_code->getUnlimit($scene, [
            'page'       => 'pages/card/card',
            'is_hyaline' => true,
            'width'      => 248,
        ]);
        if (!$response instanceof StreamResponse) {
            throw new \Exception($response['errmsg'], $response['errcode']);
        }
        // 图片二进制流
        return $response->getBodyContents();
    }

    /**
     * 生成文章分享二维码
     * @param int $userId 用户 id
     * @param int $urlId
     * @return string
     * @throws \Exception
     */
    public static function genStoryQrcode(string $userId, int $urlId = 0): string
    {
        $scene    = "cardId={$userId}&urlId={$urlId}";
        $response = app('callingCardsWechat')->app_code->getUnlimit($scene, [
            'page'       => 'pages/card/hot-news-detail',
            'is_hyaline' => true,
        ]);
        if (!$response instanceof StreamResponse) {
            throw new \Exception($response['errmsg'], $response['errcode']);
        }
        // 图片二进制流
        return $response->getBodyContents();
    }

    /*
     * 微信提交加盟商线索
     */
    public static function addFranchiseeClues(
        $name,
        $mobile,
        $openid,
        $province,
        $city,
        $district,
        $detailAddress,
        $invitorId,
        $clueId,
        $clientIp = '',
        $remark = ''
    ) {
        $franchiseeClue                = new FeishuCallingCardFranchiseeClue();
        $franchiseeClue->name          = $name;
        $franchiseeClue->mobile        = $mobile;
        $franchiseeClue->openid        = $openid;
        $franchiseeClue->province      = $province;
        $franchiseeClue->city          = $city;
        $franchiseeClue->district      = $district;
        $franchiseeClue->detailAddress = $detailAddress;
        $franchiseeClue->invitorId     = $invitorId;
        $franchiseeClue->clueId        = $clueId;
        $franchiseeClue->clientIp      = $clientIp;
        $franchiseeClue->remark        = mb_substr($remark, 0, 255);
        $franchiseeClue->save();
    }


}
